import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/api/api_common.dart';
import 'package:tender_flutter/page/home/api/api_home.dart';
import 'package:tender_flutter/page/home/item/market_list_cell.dart';
import 'package:tender_flutter/page/home/model/city_entity.dart';
import 'package:tender_flutter/page/home/model/common_tag_model.dart';
import 'package:tender_flutter/page/home/model/market_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/drop_down_menu/drop_down_address_widget.dart';
import 'package:tender_flutter/widgets/drop_down_menu/drop_dpwm_list_widget.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';
import 'package:tender_flutter/widgets/search_app_bar.dart';

class MarketSearchPage extends StatefulWidget {
  @override
  _MarketSearchPageState createState() => _MarketSearchPageState();
}

class _MarketSearchPageState extends State<MarketSearchPage> {
  List<String> _dropDownHeaderItemStrings = ['全国', '类型', '行业类别', '发布时间'];
  CityEntity _selectCityModel;
  CommonTagModel _selectTypeModel;
  CommonTagModel _selectIndustryModel;
  CommonTagModel _selectTimeModel;
  String _keyword;

  /// 筛选菜单组件
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  /// 刷新组件
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<MarketEntity>> _listFuture;

  Future<List<CommonTagModel>> _filterIndustryFuture;

  Future<List<CommonTagModel>> _filterTimesFuture;

  LoadState _loadState = LoadState.State_Loading;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  /// 列表数据
  List<MarketList> _dataLists = [];

  /// 类型数据
  List<CommonTagModel> _typeDatas = [
    CommonTagModel(strId: "0", title: "全部", isSelected: true),
    CommonTagModel(strId: "1", title: "供应", isSelected: false),
    CommonTagModel(strId: "2", title: "需求", isSelected: false)
  ];

  /// 行业类别数据
  List<CommonTagModel> _industryDatas = [];

  GlobalKey _scaffoldKey = GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();

  /// 手动刷新数据
  void _manualRefersh() {
    if (_loadState == LoadState.State_Success && _refreshController != null) {
      _refreshController.requestRefresh();
    } else {
      _onRefresh();
    }
  }

  ///下拉刷新
  void _onRefresh() {
    page = 1;
    setState(() {
      _listFuture = _getData();
    });
  }

  /// 加载更多
  void _onLoading() {
    page += 1;
    setState(() {
      _listFuture = _getData();
    });
  }

  /// 获取数据
  Future<ApiResponse<MarketEntity>> _getData() async {
    var response = await ApiHome.getMarketList(
      areaCode: _selectCityModel != null ? _selectCityModel.id : null,
      type: _selectTypeModel != null ? _selectTypeModel.id : null,
      industryId: _selectIndustryModel != null ? _selectIndustryModel.id : null,
      keyword: _keyword != null ? _keyword : null,
      beginTime:
          _selectTimeModel != null ? _selectTimeModel.value.split(',')[0] : "",
      endTime:
          _selectTimeModel != null ? _selectTimeModel.value.split(',')[1] : "",
      page: page,
      pageCount: pageCount,
    );
    return response;
  }

  /// 获取行业类别
  Future<List<CommonTagModel>> _getIndustryCategory() async {
    if (_industryDatas != null && _industryDatas.isNotEmpty) {
      return _industryDatas;
    }
    var response =
        await ApiHome.getMarketIndustryCategory<List<CommonTagModel>>();
    _industryDatas = response.result;

    for (CommonTagModel tagModel in _industryDatas) {
      tagModel.isSelected = false;
    }
    _industryDatas.insert(0,
        CommonTagModel(strId: "0", title: "全部", value: "", isSelected: true));
    return _industryDatas;
  }

  FutureBuilder<ApiResponse<MarketEntity>> buildFutureBuilder() {
    return FutureBuilder(
        future: _listFuture,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<MarketEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              MarketEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            state: _loadState,
            successWidget: _initList(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _listFuture = _getData();
    _filterIndustryFuture = _getIndustryCategory();
    _filterTimesFuture = ApiHome.getFilterTimesDatas();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      key: _scaffoldKey,
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _initBody(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return SearchAppBar(context, searchCallback: (value) {
      FocusScope.of(context).requestFocus(FocusNode());
      _keyword = value;
      _refreshController.requestRefresh();
    });
  }

  /// 筛选菜单
  Widget _initBody() {
    return Stack(
      key: _stackKey,
      children: <Widget>[
        Column(
          children: <Widget>[
            // 下拉菜单头部
            GZXDropDownHeader(
              height: ScreenAdapter.height(90),
              // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
              items: [
                GZXDropDownHeaderItem(_dropDownHeaderItemStrings[0]),
                GZXDropDownHeaderItem(_dropDownHeaderItemStrings[1]),
                GZXDropDownHeaderItem(_dropDownHeaderItemStrings[2]),
                GZXDropDownHeaderItem(_dropDownHeaderItemStrings[3]),
              ],
              // GZXDropDownHeader对应第一父级Stack的key
              stackKey: _stackKey,
              // controller用于控制menu的显示或隐藏
              controller: _dropdownMenuController,
              // 当点击头部项的事件，在这里可以进行页面跳转或openEndDrawer
              onItemTap: (index) {
                // if (index == 3) {
                //   _dropdownMenuController.hide();
                //   _scaffoldKey.currentState.openEndDrawer();
                // }
              },
              // 文字样式
              style: TextStyle(
                  color: ThemeColors.colorType1,
                  fontSize: ScreenAdapter.sp(28)),
              // 下拉时文字样式
              dropDownStyle: TextStyle(
                fontSize: ScreenAdapter.sp(28),
                color: ThemeColors.colorType6,
              ),
              // 图标颜色
              iconColor: ThemeColors.colorType7,
              // 下拉时图标颜色
              iconDropDownColor: ThemeColors.colorType6,
            ),
            Expanded(
              child: buildFutureBuilder(),
            ),
          ],
        ),
        // 下拉菜单
        GZXDropDownMenu(
          // controller用于控制menu的显示或隐藏
          controller: _dropdownMenuController,
          // 下拉菜单显示或隐藏动画时长
          animationMilliseconds: 300,
          dropdownMenuChanging: (isShow, index) {},
          dropdownMenuChanged: (isShow, index) {},
          // 下拉菜单，高度自定义，你想显示什么就显示什么，完全由你决定，你只需要在选择后调用_dropdownMenuController.hide();即可
          menus: [
            GZXDropdownMenuBuilder(
                dropDownHeight: 40 * 8.0,
                dropDownWidget: FutureBuilder(
                    future: ApiCommon.getCityDatas(),
                    builder: (BuildContext context,
                        AsyncSnapshot<List<CityEntity>> snapshot) {
                      if (snapshot.hasData) {
                        return DropMenuAddressWidget(
                          cityDatas: snapshot.data,
                          selectCityCallback:
                              (levelIndex, itemIndex, cityModel) {
                            if (levelIndex == 1) {
                              _selectCityModel = cityModel;
                              _dropDownHeaderItemStrings[0] = cityModel.title;
                              _dropdownMenuController.hide();
                              _manualRefersh();
                            }
                            setState(() {});
                          },
                        );
                      } else {
                        return Container();
                      }
                    })),
            GZXDropdownMenuBuilder(
                dropDownHeight: ScreenAdapter.height(90) * 3,
                dropDownWidget: DropDownListWidget(
                  listDatas: _typeDatas,
                  selectListItemCallback: (itemIndex, tagModel) {
                    _selectTypeModel = tagModel;
                    _dropDownHeaderItemStrings[1] =
                        _selectTypeModel.title == '全部'
                            ? '类型'
                            : _selectTypeModel.title;
                    _dropdownMenuController.hide();
                    setState(() {});
                    _manualRefersh();
                  },
                )),
            GZXDropdownMenuBuilder(
                dropDownHeight: ScreenAdapter.height(80) * 6,
                dropDownWidget: FutureBuilder(
                    future: _filterIndustryFuture,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<CommonTagModel>> snapshot) {
                      if (snapshot.hasData) {
                        print(snapshot.data.length);
                        return DropDownListWidget(
                          listDatas: snapshot.data,
                          selectListItemCallback: (itemIndex, tagModel) {
                            _selectIndustryModel = tagModel;
                            _dropDownHeaderItemStrings[2] =
                                _selectIndustryModel.title == '全部'
                                    ? '行业类别'
                                    : _selectIndustryModel.title;
                            _dropdownMenuController.hide();
                            setState(() {});
                            _manualRefersh();
                          },
                        );
                      } else {
                        return Container();
                      }
                    })),
            GZXDropdownMenuBuilder(
                dropDownHeight: ScreenAdapter.height(80) * 6.0,
                dropDownWidget: FutureBuilder(
                    future: _filterTimesFuture,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<CommonTagModel>> snapshot) {
                      if (snapshot.hasData) {
                        return DropDownListWidget(
                          listDatas: snapshot.data,
                          selectListItemCallback: (itemIndex, tagModel) {
                            _selectTimeModel = tagModel;
                            _dropDownHeaderItemStrings[3] =
                                _selectTimeModel.title == '全部'
                                    ? '发布时间'
                                    : _selectTimeModel.title;
                            _dropdownMenuController.hide();
                            setState(() {});
                            _manualRefersh();
                          },
                        );
                      } else {
                        return Container();
                      }
                    })),
          ],
        ),

        Positioned(
          bottom: 60,
          width: ScreenAdapter.screenWidth(),
          child: Align(
            alignment: Alignment.bottomCenter,
            child: GestureDetector(
                onTap: () {
                  LRouter.navigatorCtx(context).push(Routes.marketPulishPage);
                },
                child: Container(
                  width: ScreenAdapter.width(280),
                  height: ScreenAdapter.height(80),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: ThemeColors.colorType6,
                      borderRadius:
                          BorderRadius.circular(ScreenAdapter.width(45)),
                      boxShadow: [
                        BoxShadow(
                          blurRadius: 1, //阴影范围
                          spreadRadius: 1, //阴影浓度
                          color: ThemeColors.colorType21, //阴影颜色
                        ),
                      ]),
                  child: Text("发布",
                      style: TextStyle(
                          fontSize: ScreenAdapter.sp(30),
                          color: ThemeColors.colorWhite)),
                )),
          ),
        )
      ],
    );
  }

  /// 主体内容列表
  Widget _initList() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.separated(
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            MarketList model = _dataLists[index];
            return MarketListCell(
                data: model,
                keyword: _keyword,
                onTap: () {
                  LRouter.navigatorCtx(context).push(Routes.marketDetailPage,
                      queryParams: {"marketId": model.id.toString()});
                });
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: ScreenAdapter.height(10),
              color: ThemeColors.colorType11,
            );
          },
        ));
  }
}
